import os 
import shutil 
  
def init_dir(target_dir):
    """
    初始化目录
    """
    if os.path.exists(target_dir):
        shutil.rmtree(target_dir)
    os.makedirs(target_dir)    

def rename_files_in_directory(directory):  
    """  
    遍历目录中的所有文件，并使用提供的函数修改文件名。  
  
    :param directory: 要遍历的目录路径。  
    :param name_function: 一个函数，接收当前文件名并返回新文件名。  
    """  
    # 遍历目录中的所有文件和子目录  
    for root, dirs, files in os.walk(directory):  
        for file_name in files:  
            # 构建当前文件的完整路径  
            old_file_path = os.path.join(root, file_name)  
              
            # 使用提供的函数获取新文件名  
            new_file_name =file_name.split("][")[2]+"."+file_name.split(".")[1]
              
            # 构建新文件的完整路径  
            new_file_path = os.path.join(root, new_file_name)

            # 重命名文件  
            os.rename(old_file_path, new_file_path)  
            print(f'Renamed: {old_file_path} -> {new_file_path}')  
  
def mkv_to_mp4(source_dir,target_dir):
    """
        mkv格式视频转mp4格式视频
    """
    init_dir(target_dir)
    for root, dirs, files in os.walk(source_dir):
        for file_name in files:  
            if not file_name.endswith("mkv"):
                continue
            # cmd=rf'ffmpeg -i "{os.path.join(root, file_name)}" -vcodec copy -acodec copy -scodec mov_text "{target_dir}\{file_name.split(".")[0]}.mp4" '
            inner_name = os.path.join(root, file_name)
            inner_name = inner_name.replace("\\","\\\\").replace(":","\\:")
            cmd=f'ffmpeg -i "{os.path.join(root, file_name)}" -vf "subtitles=\'{inner_name}\':si=0" -c:v libx264 -c:a aac "{target_dir}\\{file_name.split(".")[0]}.mp4"'
            print(cmd)
            os.system(cmd)
            # os.remove(os.path.join(root, file_name))
           

def split_mp4(split_data,target_dir):
    """
    切分MP4视频
    """
    init_dir(target_dir)
    i=1
    with open(f"{target_dir}\\split.txt",mode="w") as fs:
        for split_item in split_data:
            file_path = split_item["file_path"]
            intervals = split_item["intervals"]
            for interval in intervals:
                cmd =f'ffmpeg -i "{file_path}" -ss "{interval["ss"]}" -to "{interval["to"]}" -c copy "{target_dir}\\{i}.mp4"'
                print(cmd)
                os.system(cmd)
                fs.write(f"file '{target_dir}\\{i}.mp4'\n")
                i+=1

def concat_mp4(concat_file_path,target_dir):
    """
    拼接视频
    """
    init_dir(target_dir)
    cmd=f"ffmpeg -f concat -safe 0 -i {concat_file_path} -c copy {target_dir}\\output.mp4"  
    print(cmd)
    os.system(cmd) 



if __name__ == "__main__":
    # 指定要遍历的目录  
    source_dir = r'D:\video_tmp\source' 
    mp4_dir = r'D:\video_tmp\mp4'
    split_dir = r'D:\video_tmp\split'
    output_dir= r'D:\video_tmp\output'
    split_data = [
        {
            "file_path":r"D:\video_tmp\mp4\524.mp4",
            "intervals":[
                {
                    "ss":"00:07:02",
                    "to":"00:15:50"
                },{
                    "ss":"00:18:05",
                    "to":"00:21:01"
                }
            ]
        },
        {
            "file_path":r"D:\video_tmp\mp4\525.mp4",
            "intervals":[
                {
                    "ss":"00:05:07",
                    "to":"00:08:59"
                },{
                    "ss":"00:12:29",
                    "to":"00:18:00"
                }
            ]
        }
    ]
    # 调用函数进行文件重命名  
    # rename_files_in_directory(source_dir)
    # mkv 转 MP4
    # mkv_to_mp4(source_dir,mp4_dir)
    # 切分视频
    split_mp4(split_data,split_dir)
    concat_mp4(split_dir+"\\split.txt",output_dir)



